<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Simple Browser</title>
    <style>
        :root {
            --primary: #2c3e50;
            --accent: #3498db;
        }

        body {
            margin: 0;
            height: 100vh;
            display: flex;
            flex-direction: column;
            font-family: system-ui;
        }

        .toolbar {
            padding: 8px;
            background: #f8f9fa;
            display: flex;
            align-items: center;
            gap: 8px;
            border-bottom: 1px solid #e0e0e0;
        }

        #page-title {
            flex: 0 0 auto;
            font-size: 16px;
            color: var(--primary);
            margin-right: 16px;
        }

        .nav-btn {
            padding: 8px 12px;
            border: none;
            border-radius: 4px;
            background: var(--primary);
            color: white;
            cursor: pointer;
            transition: opacity 0.2s;
        }

        .nav-btn:hover {
            opacity: 0.8;
        }

        #url-bar {
            flex: 1;
            padding: 8px 16px;
            border: 1px solid #ddd;
            border-radius: 20px;
            font-size: 14px;
        }

        .menu-container {
            position: relative;
            display: inline-block;
        }

        .menu-btn {
            padding: 8px 16px;
            background: none;
            border: none;
            cursor: pointer;
        }

        .dropdown-menu {
            position: absolute;
            width: 200px;
            background: white;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
            border-radius: 8px;
            padding: 8px 0;
            display: none;
            z-index: 100;
        }

        .menu-item {
            padding: 8px 16px;
            display: flex;
            align-items: center;
            gap: 8px;
            cursor: pointer;
        }

        .menu-item svg {
            vertical-align: middle;
        }

        .menu-item:hover {
            background: #f5f6fa;
        }

        #webview {
            flex: 1;
            border: 1px solid #ccc;
            width: 100%;
            height: calc(100vh - 160px);
        }

        #home-bottom {
            background-color: #f0f0f0;
            padding: 10px;
        }

        #bookmark-list,
        #history-list {
            list-style-type: none;
            padding: 0;
        }

        .bookmark-item,
        .history-item {
            margin: 5px 0;
            cursor: pointer;
        }

        .bookmark-item:hover,
        .history-item:hover {
            text-decoration: underline;
        }

        #pull-to-refresh {
            display: none;
            justify-content: center;
            align-items: center;
            height: 40px;
            background-color: #f5f5f5;
            width: 100%;
        }

        .nav-container {
            display: flex;
            justify-content: center;
            flex-wrap: wrap;
            gap: 20px;
            padding: 20px;
            max-width: 1200px;
            margin: 0 auto;
        }

        .nav-item {
            display: flex;
            flex-direction: column;
            align-items: center;
            width: calc(25% - 20px);
            min-width: 120px;
            height: 140px;
            background-color: #fff;
            border: 2px solid #eee;
            border-radius: 15px;
            cursor: pointer;
            transition: all 0.3s ease;
            padding: 15px;
        }

        @media (max-width: 768px) {
            .nav-item {
                width: calc(50% - 20px);
            }
        }

        .nav-item:hover {
            transform: scale(1.05);
            box-shadow: 0 0 15px rgba(0, 0, 0, 0.1);
            border-color: var(--accent);
        }

        .nav-item svg {
            width: 60px;
            height: 60px;
            fill: var(--accent);
        }

        .nav-item p {
            margin: 10px 0 0;
            font-size: 14px;
            color: #333;
            text-align: center;
        }

        #nav-page {
            display: block;
            padding: 20px;
            flex-grow: 1;
            overflow-y: auto;
        }

        /* 新增：搜索建议样式 */
        .suggestion-item {
            padding: 8px 16px;
            cursor: pointer;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .suggestion-item:hover {
            background-color: #f5f5f5;
        }
    </style>
</head>

<body>
    <!-- 工具栏 -->
    <div class="toolbar">
        <div id="page-title">简约浏览器</div>
        <button class="nav-btn" onclick="history.back()">←</button>
        <button class="nav-btn" onclick="history.forward()">→</button>
        <button class="nav-btn" id="reload-btn" onclick="reloadPage()">↻</button>
        <input type="text" id="url-bar" placeholder="输入网址或搜索内容">

        <div class="menu-container">
            <button class="menu-btn" onclick="toggleMenu()">☰</button>
            <div class="dropdown-menu" id="mainMenu">
                <div class="menu-item" onclick="showAbout()">
                    <svg width="16" height="16" viewBox="0 0 24 24"><path fill="currentColor" d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 15h-2v-6h2v6zm0-8h-2V7h2v2z"></path></svg>
                    关于浏览器
                </div>
                <div class="menu-item" onclick="showSearchEngineMenu()">
                    <svg width="16" height="16" viewBox="0 0 24 24"><path fill="currentColor" d="M12 8a4 4 0 1 0 0 8 4 4 0 0 0 0-8zm0 14c-3.31 0-6-2.69-6-6s2.69-6 6-6 6 2.69 6 6-2.69 6-6 6z"></path></svg>
                    搜索引擎 <span id="search-engine-name">百度</span>
                </div>
                <div class="menu-item" onclick="toggleAdBlock()">
                    <svg width="16" height="16" viewBox="0 0 24 24"><path fill="currentColor" d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zM4 12c0-4.42 3.58-8 8-8 1.85 0 3.55.63 4.9 1.69L5.69 16.9C4.63 15.55 4 13.85 4 12zm8 8c-1.85 0-3.55-.63-4.9-1.69L18.31 7.1C19.37 8.45 20 10.15 20 12c0 4.42-3.58 8-8 8z"></path></svg>
                    广告屏蔽 <span id="ad-block-status">(关闭)</span>
                </div>
                <div class="menu-item" onclick="showBookmarks()">
                    <svg width="16" height="16" viewBox="0 0 24 24"><path fill="currentColor" d="M17 3H7c-1.1 0-2.9-2-2V5c0-1.1-.9-2-2-2z"></path></svg>
                    收藏/历史
                </div>
                <div class="menu-item" onclick="savePage()">
                    <svg width="16" height="16" viewBox="0 0 24 24"><path fill="currentColor" d="M14 2H6c-1.1 0-2.9-2-2v16c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V8l-6-6zM6 20V4h7v5h5v11H6z" /></svg>
                    归档网页
                </div>
                <div class="menu-item" onclick="showUASettings()">
                    <svg width="16" height="16" viewBox="0 0 24 24"><path fill="currentColor" d="M12 18c-2.21 0-4-1.79-4-4s1.79-4 4-4 4 1.79 4 4-1.79 4-4 4zm0-6c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2z"></path></svg>
                    UA设置
                </div>
            </div>
        </div>
    </div>

    <!-- 网页视图 -->
    <iframe id="webview" src="about:blank"></iframe>

    <!-- 首页下方差异化区域 -->
    <div id="home-bottom"></div>

    <!-- 收藏/历史弹出框 -->
    <div id="bookmark-popup" style="display: none; position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); background-color: white; padding: 20px; box-shadow: 0 0 10px rgba(0, 0, 0, 0.3); z-index: 101;">
        <h2>收藏列表</h2>
        <ul id="bookmark-list"></ul>
        <button onclick="closeBookmarkPopup()">关闭</button>
    </div>

    <div id="history-popup" style="display: none; position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); background-color: white; padding: 20px; box-shadow: 0 0 10px rgba(0, 0, 0, 0.3); z-index: 101;">
        <h2>历史记录</h2>
        <ul id="history-list"></ul>
        <button onclick="closeHistoryPopup()">关闭</button>
    </div>

    <!-- 下拉刷新区域 -->
    <div id="pull-to-refresh">下拉刷新</div>

    <!-- 搜索建议列表 -->
    <div id="search-suggestions" style="position: absolute; width: 100%; background: white; border: 1px solid #ddd; display: none;"></div>

    <script>
        const webview = document.getElementById('webview');
        const urlBar = document.getElementById('url-bar');
        const pageTitle = document.getElementById('page-title');
        const reloadBtn = document.getElementById('reload-btn');
        const searchEngineName = document.getElementById('search-engine-name');
        const adBlockStatus = document.getElementById('ad-block-status');
        const bookmarkList = document.getElementById('bookmark-list');
        const historyList = document.getElementById('history-list');
        const bookmarkPopup = document.getElementById('bookmark-popup');
        const historyPopup = document.getElementById('history-popup');
        const pullToRefresh = document.getElementById('pull-to-refresh');
        const suggestionContainer = document.getElementById('search-suggestions');

        // 搜索引擎配置
        const searchEngines = {
            baidu: 'https://www.baidu.com/s?wd=',
            google: 'https://www.google.com/search?q=',
            bing: 'https://www.bing.com/search?q='
        };
        let defaultSearchEngine = localStorage.getItem('defaultSearchEngine') || 'baidu';
        searchEngineName.textContent = defaultSearchEngine;

        // 广告屏蔽配置
        let adBlockEnabled = JSON.parse(localStorage.getItem('adBlockEnabled')) || false;
        const adBlockRules = [/广告/i, /ad/i, /banner/i, '.ad-container', '#advertisement', '.sponsor'];

        // 收藏/历史记录
        let bookmarks = JSON.parse(localStorage.getItem('bookmarks')) || [];
        let historyRecords = JSON.parse(localStorage.getItem('history')) || [];

        // UA设置
        let currentUA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36";

        // 下拉刷新变量
        let startY = 0, distanceY = 0;

        // 页面加载事件
        webview.addEventListener('load', onPageLoad);

        function onPageLoad() {
            try {
                const currentUrl = webview.src;
                urlBar.value = currentUrl;
                const title = webview.contentWindow.document.title;
                pageTitle.textContent = title || '无标题网页';

                // 记录历史（去重）
                if (historyRecords.length === 0 || historyRecords[historyRecords.length - 1] !== currentUrl) {
                    historyRecords.push(currentUrl);
                    localStorage.setItem('history', JSON.stringify(historyRecords));
                }

                // 初始化广告屏蔽
                adBlockStatus.textContent = `(${adBlockEnabled ? '开启' : '关闭'})`;
                if (adBlockEnabled) activateAdBlock();
            } catch (error) {
                pageTitle.textContent = '跨域限制，无法获取标题';
            }
        }

        // 地址栏导航
        urlBar.addEventListener('keypress', (e) => e.key === 'Enter' && navigate());

        function navigate() {
            const input = urlBar.value.trim();
            if (!input) return;

            let url = input;
            if (!/^https?:\/\//i.test(url)) {
                url = url.includes('.') 
                    ? `http://${url}` 
                    : searchEngines[defaultSearchEngine] + encodeURIComponent(url);
            }

            if (isValidUrl(url)) {
                webview.src = url;
                suggestionContainer.style.display = 'none';
            } else {
                alert('无效的网址或搜索词');
            }
        }

        // 刷新页面
        function reloadPage() {
            webview.src = webview.src; // 触发load事件
        }

        // 广告屏蔽功能
        function toggleAdBlock() {
            adBlockEnabled = !adBlockEnabled;
            localStorage.setItem('adBlockEnabled', adBlockEnabled);
            adBlockStatus.textContent = `(${adBlockEnabled ? '开启' : '关闭'})`;
            adBlockEnabled ? activateAdBlock() : deactivateAdBlock();
        }

        function activateAdBlock() {
            const observer = new MutationObserver(mutations => {
                mutations.forEach(mutation => {
                    mutation.addedNodes.forEach(node => node.nodeType === 1 && applyAdBlockRules(node));
                });
            });
            observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['class', 'id'] });
            applyAdBlockRules(document.body);
        }

        function applyAdBlockRules(element) {
            if (!adBlockEnabled) return;
            const text = element.textContent || '', cls = element.className || '', id = element.id || '';
            if (adBlockRules.some(rule => rule.test(text) || rule.test(cls) || rule.test(id))) {
                element.style.display = 'none';
            }
            element.children.forEach(child => applyAdBlockRules(child));
        }

        function deactivateAdBlock() {
            document.querySelectorAll('[style*="display: none"]').forEach(el => el.removeAttribute('style'));
        }

        // 搜索引擎切换
        function showSearchEngineMenu() {
            const menu = document.createElement('div');
            menu.className = 'dropdown-menu';
            menu.style.position = 'absolute';
            menu.style.top = '36px';
            menu.style.right = '8px';

            Object.keys(searchEngines).forEach(engine => {
                const item = document.createElement('div');
                item.className = 'menu-item';
                item.textContent = engine;
                item.addEventListener('click', () => {
                    defaultSearchEngine = engine;
                    localStorage.setItem('defaultSearchEngine', engine);
                    searchEngineName.textContent = engine;
                    menu.remove();
                });
                menu.appendChild(item);
            });
            document.body.appendChild(menu);
        }

        // 搜索建议（带防抖）
        let debounceTimer;
        urlBar.addEventListener('input', () => {
            clearTimeout(debounceTimer);
            debounceTimer = setTimeout(() => {
                const input = urlBar.value.trim();
                if (input.length < 2) {
                    suggestionContainer.style.display = 'none';
                    return;
                }
                // 生成历史记录建议
                const suggestions = historyRecords.filter(h => h.includes(input)).slice(0, 5);
                // 渲染建议
                suggestionContainer.innerHTML = suggestions.map(s => `<div class="suggestion-item">${s}</div>`).join('');
                suggestionContainer.style.display = 'block';
                suggestionContainer.style.left = urlBar.offsetLeft + 'px';
                suggestionContainer.style.width = urlBar.offsetWidth + 'px';
                // 点击建议项导航
                suggestionContainer.querySelectorAll('.suggestion-item').forEach(item => {
                    item.addEventListener('click', () => {
                        urlBar.value = item.textContent;
                        suggestionContainer.style.display = 'none';
                        navigate();
                    });
                });
            }, 300);
        });

        // 收藏/历史功能
        function addBookmark() {
            const url = webview.src;
            if (bookmarks.includes(url)) { alert('已收藏'); return; }
            bookmarks.push(url);
            localStorage.setItem('bookmarks', JSON.stringify(bookmarks));
            alert('收藏成功');
        }

        function displayBookmarks() {
            bookmarkList.innerHTML = '';
            bookmarks.forEach(url => {
                const li = document.createElement('li');
                li.className = 'bookmark-item';
                li.textContent = url;
                li.addEventListener('click', () => { webview.src = url; closeBookmarkPopup(); });
                bookmarkList.appendChild(li);
            });
        }

        function updateHistory(url) {
            if (historyRecords[historyRecords.length - 1] !== url) {
                historyRecords.push(url);
                localStorage.setItem('history', JSON.stringify(historyRecords));
            }
        }

        function displayHistory() {
            historyList.innerHTML = '';
            historyRecords.forEach(url => {
                const li = document.createElement('li');
                li.className = 'history-item';
                li.textContent = url;
                li.addEventListener('click', () => { webview.src = url; closeHistoryPopup(); });
                historyList.appendChild(li);
            });
        }

        // 下拉刷新
        webview.addEventListener('touchstart', e => startY = e.touches[0].clientY);
        webview.addEventListener('touchmove', e => {
            distanceY = e.touches[0].clientY - startY;
            distanceY > 50 && (pullToRefresh.style.display = 'flex');
        });
        webview.addEventListener('touchend', () => {
            if (distanceY > 80) {
                reloadPage();
                pullToRefresh.style.display = 'none';
            } else {
                pullToRefresh.style.display = 'none';
            }
            distanceY = 0;
        });

        // 弹出框操作
        function showBookmarks() { displayBookmarks(); bookmarkPopup.style.display = 'block'; }
        function showHistory() { displayHistory(); historyPopup.style.display = 'block'; }
        function closeBookmarkPopup() { bookmarkPopup.style.display = 'none'; }
        function closeHistoryPopup() { historyPopup.style.display = 'none'; }

        // UA设置
        function showUASettings() {
            const ua = prompt("选择UA类型：\n1. 电脑\n2. iPad\n3. 安卓\n4. 苹果手机", "1");
            switch (ua) {
                case '1': currentUA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36"; break;
                case '2': currentUA = "Mozilla/5.0 (iPad; CPU OS 15_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Safari/605.1.15"; break;
                case '3': currentUA = "Mozilla/5.0 (Linux; Android 12; SM-G991B) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Mobile Safari/537.36"; break;
                case '4': currentUA = "Mozilla/5.0 (iPhone; CPU iPhone OS 15_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Mobile/15E148 Safari/605.1.15"; break;
            }
            alert(`UA已设置为：${currentUA.split(') ')[1]}`);
        }

        // 其他功能
        function showAbout() {
            alert(`简约浏览器\n版本 1.0\n当前网址: ${webview.src}\n广告屏蔽：${adBlockEnabled ? '开启' : '关闭'}`);
        }

        function savePage() {
            const a = document.createElement('a');
            a.href = webview.src;
            a.download = `网页归档_${Date.now()}.html`;
            a.click();
            alert("已尝试下载当前网页（可能受跨域限制影响）");
        }

        // 关闭菜单和建议
        document.addEventListener('click', e => {
            const target = e.target;
            if (!target.closest('.toolbar, .menu-container, .suggestion-item, #search-suggestions')) {
                document.getElementById('mainMenu').style.display = 'none';
                suggestionContainer.style.display = 'none';
            }
        });

        function toggleMenu() {
            document.getElementById('mainMenu').style.display = document.getElementById('mainMenu').style.display === 'block' ? 'none' : 'block';
        }

        function isValidUrl(url) {
            try { new URL(url); return true; } catch { return false; }
        }
    </script>
</body>

</html>
